var GSVPANO = GSVPANO || {};
GSVPANO.PanoLoader = function (parameters) {
  var _parameters = parameters || {},
    _location,
    _zoom,
    _panoId,
    _count = 0,
    _total = 0,
    _canvas = document.createElement("canvas"),
    _ctx = _canvas.getContext("2d"),
    _level,
    _xcount, //横着有多少张
    _ycount,
    rotation = 0,
    copyright = "",
    links = [],
    lat = "",
    lng = "",
    loading = false,
    onSizeChange = null,
    onPanoramaLoad = null,
    _savePath = null;

  this.setProgress = function (p) {
    if (this.onProgress) {
      this.onProgress(p);
    }
  };

  this.throwError = function (message) {
    if (this.onError) this.onError(message);
    else console.error(message);
  };

  this.adaptTextureToZoom = function () {
    var n = 512;
    if (_xcount == 7) {
      n = 416;
    }
    _canvas.width = n * Math.pow(2, _zoom);
    _canvas.height = n * Math.pow(2, _zoom - 1);
    _ctx.translate(_canvas.width, 0);
    _ctx.scale(-1, 1);
  };

  this.composeFromTile = function (x, y, texture) {
    _ctx.drawImage(texture, x * 512, y * 512);
    _count++;

    this.setProgress(Math.round((_count * 100) / _total));

    if (_count === _total) {
      this.canvas = _canvas;
      this.loading = false;
      if (this.onPanoramaLoad) {
        this.onPanoramaLoad();
      }
    }
  };

  this.composePanorama = function (getIamgeApi) {
    this.setProgress(0);

    var w,
      h,
      self = this,
      x,
      y;
    w = _xcount;
    h = _ycount;
    // w = 7;
    // h = 4;
    _count = 0;
    _total = w * h;
    var param = {
      panoId: _panoId,
      fileName: this.getFileName(parseFloat(this.lng), parseFloat(this.lat)),
      zoom: _zoom,
    };

    getIamgeApi(param).then((data) => {
      for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++) {
          var xy = x.toString() + y.toString();
          (function (x, y) {
            var img = new Image();
            img.addEventListener("load", function () {
              self.composeFromTile(x, y, this);
            });
            img.crossOrigin = "";
            img.src = data[xy];
          })(x, y);
        }
      }
    });

    // $.get(
    //   "https://engine.piesat.cn/hr_data/getImageByPanoId",
    //   param,
    //   function (data) {
    //     for (y = 0; y < h; y++) {
    //       for (x = 0; x < w; x++) {
    //         var xy = x.toString() + y.toString();
    //         (function (x, y) {
    //           var img = new Image();
    //           img.addEventListener("load", function () {
    //             self.composeFromTile(x, y, this);
    //           });
    //           img.crossOrigin = "";
    //           img.src = data[xy];
    //         })(x, y);
    //       }
    //     }
    //   },
    //   "json"
    // );
  };

  this.getFileName = function (lng, lat) {
    var columnsCount = 14400;
    var c = Math.floor((lng + 180) * 40);
    var r = Math.floor((lat + 90) * 40);
    return r * columnsCount + c;
  };

  this.load = function (panoId, lat, lng, getJsonApi, getImageApi) {
    var self = this;
    self.panoId = panoId;
    if (self.loading) return;
    var requestObj = {
      panoId: panoId,
      fileName: self.getFileName(parseFloat(lng), parseFloat(lat)),
    };
    if (isNaN(requestObj.fileName)) {
      requestObj.fileName = filecode;
    }
    getJsonApi(requestObj).then((res) => {
      if (res != "" && res != null) {
        var result = res;
        if (self.onPanoramaData) self.onPanoramaData(res);
        // 计算_x的最大值
        _level = result.Location.zoomLevels;
        _xcount = Math.ceil(
          result.Data.image_width /
            (result.Data.tile_width * Math.pow(2, _level - parseInt(_zoom)))
        );
        _ycount = Math.ceil(
          result.Data.image_height /
            (result.Data.tile_height * Math.pow(2, _level - parseInt(_zoom)))
        );
        // 根据x_count大小设置canvas
        self.adaptTextureToZoom();
        self.links = result.Links;
        self.lng = result.Location.lng;
        self.lat = result.Location.lat;
        self.heading = result.Projection.pano_yaw_deg;
        _panoId = panoId;
        self.composePanorama(getImageApi);
        document.querySelector("#streetLngVal").innerHTML = parseFloat(
          result.Location.lng
        );
        document.querySelector("#streetLatVal").innerHTML = parseFloat(
          result.Location.lat
        );
        document.querySelector("#streetDateVal").innerHTML =
          result.Data.image_date;
        var address =
          result.Location.country +
          "  " +
          (result.Location.region == undefined ? "" : result.Location.region) +
          "  " +
          result.Location.description;
        document.querySelector("#streetLocationVal").innerHTML = address;
        // parent.$("#streetView").show();
      } else {
        document.querySelector("#street-box").style.display = "none";
      }
    });
    // $.get(
    //   "https://engine.piesat.cn/hr_data/getJsonByPanoId",
    //   requestObj,
    //   function (res, err) {
    //     console.log(res);
    //     if (res != "" && res != null) {
    //       var result = JSON.parse(res);
    //       if (self.onPanoramaData) self.onPanoramaData(res);
    //       // 计算_x的最大值
    //       _level = result.Location.zoomLevels;
    //       _xcount = Math.ceil(
    //         result.Data.image_width /
    //           (result.Data.tile_width * Math.pow(2, _level - parseInt(_zoom)))
    //       );
    //       _ycount = Math.ceil(
    //         result.Data.image_height /
    //           (result.Data.tile_height * Math.pow(2, _level - parseInt(_zoom)))
    //       );
    //       // 根据x_count大小设置canvas
    //       self.adaptTextureToZoom();
    //       self.links = result.Links;
    //       self.lng = result.Location.lng;
    //       self.lat = result.Location.lat;
    //       self.heading = result.Projection.pano_yaw_deg;
    //       _panoId = panoId;
    //       self.composePanorama();
    //       document.querySelector("#streetLngVal").innerHTML = parseFloat(
    //         result.Location.lng
    //       );
    //       document.querySelector("#streetLatVal").innerHTML = parseFloat(
    //         result.Location.lat
    //       );
    //       document.querySelector("#streetDateVal").innerHTML =
    //         result.Data.image_date;
    //       var address =
    //         result.Location.country +
    //         "  " +
    //         (result.Location.region == undefined
    //           ? ""
    //           : result.Location.region) +
    //         "  " +
    //         result.Location.description;
    //       document.querySelector("#streetLocationVal").innerHTML = address;
    //       // parent.$("#streetView").show();
    //     } else {
    //       document.querySelector("#street-box").style.display = "none";
    //     }
    //   }
    // );
  };

  this.setZoom = function (zoom) {
    _zoom = zoom;
  };
};
